<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>socket.io 多对多聊天</title>
  <script src="js/socket.io.js"></script>
</head>
<body>
  <h3>多对多聊天室</h3>

  <input type="text" id="inputMsg">
  <button id="inputBtn">发送</button>
  <div id="msg"></div>

  <script>
    var inputMsg = document.getElementById("inputMsg");
    var inputBtn = document.getElementById("inputBtn");
    var msg = document.getElementById("msg");
    // 1. 连接到聊天室
    var clientSocket = io("ws://127.0.0.1:3000");
    // 功能1: 新用户加入服务器 广播 enter
    clientSocket.on("enter", (data) =>{
      addmsg(data, "#f00");
    });
    // 功能2: 接受所有用户发送的消息 chat
    clientSocket.on("chat",(data)=>{
      addmsg(data, "#00f");
    });

    // 功能3: 用户离开发送广播 leave
    clientSocket.on("leave",(data)=>{
      addmsg(data, "#f0f");
    });

  
    inputBtn.onclick = function () {
      // 功能4:  发送内容给服务器
      clientSocket.emit("message", inputMsg.value);
    }


    function addmsg(data, color) {
      var div = document.createElement("div");
      div.style.color = color;
      div.innerHTML = data;
      msg.appendChild(div);
    }
  </script>
</body>
</html>